package stack

import "errors"

type tStackIterator struct {
	stack *tArrayStack
	pos int
	version int64
}

var gNullStackError = errors.New("stack is null")
var gNoMoreElementError = errors.New("no more element")
var gConcurrentModificationError = errors.New("concurrent modification error")

func newStackIterator(stack *tArrayStack) IStackIterator {
	return &tStackIterator{
		stack: stack,
		pos: -1,
		version: stack.version,
	}
}

func (me *tStackIterator) More() bool {
	if me.stack == nil {
		return false
	}
	if me.version != me.stack.version {
		return false
	}
	return me.pos < me.stack.top
}

func (me *tStackIterator) Next() (error, interface{}) {
	if me.stack == nil {
		return gNullStackError, nil
	}
	if me.version != me.stack.version {
		return gConcurrentModificationError, nil
	}
	if me.pos >= me.stack.top {
		return gNoMoreElementError, nil
	}

	me.pos++
	return nil, me.stack.items[me.pos]
}
